<template>
  <view class="sms-password-container">
    <view class="page-header">
      <view class="header-title">{{ isReset ? '重置密码' : '设置密码' }}</view>
      <view class="header-subtitle">{{ isReset ? '通过短信验证码重置您的登录密码' : '通过短信验证码设置您的登录密码' }}</view>
    </view>

    <form @submit="handleSubmit">
      <!-- 手机号显示 -->
      <view class="form-item">
        <text class="form-label">手机号</text>
        <text class="phone-display">{{ phone }}</text>
      </view>

      <!-- 验证码输入 -->
      <view class="form-item">
        <text class="form-label">验证码</text>
        <view class="code-wrapper">
          <input
            class="code-input"
            type="number"
            v-model="code"
            placeholder="请输入验证码"
            maxlength="6"
          />
          <button
            class="code-btn"
            :disabled="countdown > 0 || isRequesting"
            @click="sendCode"
            type="button"
          >
            {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
          </button>
        </view>
      </view>

      <!-- 新密码 -->
      <view class="form-item">
        <text class="form-label">{{ isReset ? '新密码' : '设置密码' }}</text>
        <view class="input-wrapper">
          <input
            class="form-input"
            :type="showNewPassword ? 'text' : 'password'"
            v-model="newPassword"
            placeholder="请输入6-20位密码"
            maxlength="20"
          />
          <view class="password-toggle" @click="toggleNewPassword">
            <text class="toggle-icon">{{ showNewPassword ? '👁' : '🙈' }}</text>
          </view>
        </view>
      </view>

      <!-- 确认密码 -->
      <view class="form-item">
        <text class="form-label">确认密码</text>
        <view class="input-wrapper">
          <input
            class="form-input"
            :type="showConfirmPassword ? 'text' : 'password'"
            v-model="confirmPassword"
            placeholder="请再次输入密码"
            maxlength="20"
          />
          <view class="password-toggle" @click="toggleConfirmPassword">
            <text class="toggle-icon">{{ showConfirmPassword ? '👁' : '🙈' }}</text>
          </view>
        </view>
      </view>

      <!-- 密码强度提示 -->
      <view class="password-tips">
        <text class="tips-title">密码要求：</text>
        <text class="tips-item" :class="{ 'valid': passwordValidation.length }">• 长度6-20位</text>
        <text class="tips-item" :class="{ 'valid': passwordValidation.hasLetter }">• 包含字母</text>
        <text class="tips-item" :class="{ 'valid': passwordValidation.hasNumber }">• 包含数字</text>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" form-type="submit" :disabled="isSubmitting">
        {{ isSubmitting ? (isReset ? '重置中...' : '设置中...') : (isReset ? '重置密码' : '设置密码') }}
      </button>
    </form>
  </view>
</template>

<script>
import { userApi } from '../../api'

export default {
  data() {
    return {
      phone: '',
      code: '',
      newPassword: '',
      confirmPassword: '',
      showNewPassword: false,
      showConfirmPassword: false,
      isSubmitting: false,
      isRequesting: false,
      countdown: 0,
      timer: null,
      isReset: false // 是否为重置密码模式
    }
  },
  
  computed: {
    // 密码验证
    passwordValidation() {
      return {
        length: this.newPassword.length >= 6 && this.newPassword.length <= 20,
        hasLetter: /[a-zA-Z]/.test(this.newPassword),
        hasNumber: /\d/.test(this.newPassword)
      }
    }
  },
  
  onLoad(options) {
    // 检查是否为重置密码模式
    this.isReset = options.type === 'reset'

    // 获取用户手机号
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo && userInfo.phone) {
      this.phone = userInfo.phone
    } else {
      uni.showToast({
        title: '获取手机号失败',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  
  methods: {
    // 切换新密码显示状态
    toggleNewPassword() {
      this.showNewPassword = !this.showNewPassword
    },
    
    // 切换确认密码显示状态
    toggleConfirmPassword() {
      this.showConfirmPassword = !this.showConfirmPassword
    },
    
    // 验证手机号格式
    validatePhone(phone) {
      const phoneReg = /^1[3-9]\d{9}$/
      return phoneReg.test(phone)
    },
    
    // 发送验证码
    async sendCode() {
      if (this.isRequesting || this.countdown > 0) return
      
      if (!this.phone) {
        uni.showToast({
          title: '手机号不能为空',
          icon: 'none'
        })
        return
      }
      
      if (!this.validatePhone(this.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return
      }
      
      this.isRequesting = true
      
      try {
        uni.showLoading({
          title: '发送中...'
        })
        
        const res = await userApi.getCode({
          phone: this.phone,
          type: this.isReset ? 'resetPassword' : 'setPassword' // 根据模式设置验证码类型
        })
        
        if (res && res.code === 200) {
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
          
          // 开始倒计时
          this.countdown = 60
          this.timer = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--
            } else {
              clearInterval(this.timer)
            }
          }, 1000)
        } else {
          throw new Error(res?.message || '发送验证码失败')
        }
      } catch (error) {
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: error.message || '发送失败，请重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
        this.isRequesting = false
      }
    },
    
    // 验证密码格式
    validatePassword(password) {
      if (!password || password.length < 6 || password.length > 20) {
        return '密码长度必须为6-20位'
      }
      if (!/[a-zA-Z]/.test(password)) {
        return '密码必须包含字母'
      }
      if (!/\d/.test(password)) {
        return '密码必须包含数字'
      }
      return null
    },
    
    // 表单验证
    validateForm() {
      if (!this.code) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return false
      }
      
      if (this.code.length !== 6) {
        uni.showToast({
          title: '验证码格式不正确',
          icon: 'none'
        })
        return false
      }
      
      // 验证新密码
      const passwordError = this.validatePassword(this.newPassword)
      if (passwordError) {
        uni.showToast({
          title: passwordError,
          icon: 'none'
        })
        return false
      }
      
      // 验证确认密码
      if (this.newPassword !== this.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    // 提交表单
    async handleSubmit() {
      if (this.isSubmitting) return
      
      if (!this.validateForm()) return
      
      try {
        this.isSubmitting = true
        
        uni.showLoading({
          title: this.isReset ? '重置中...' : '设置中...'
        })

        // 获取用户信息
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo || !userInfo.id) {
          uni.showToast({
            title: '用户信息获取失败',
            icon: 'none'
          })
          return
        }

        const requestData = {
          userId: userInfo.id,
          phone: this.phone,
          code: this.code,
          password: this.newPassword
        }

        // 根据模式调用不同的API
        const res = this.isReset
          ? await userApi.resetPassword(requestData)
          : await userApi.setPasswordBySms(requestData)

        if (res && res.code === 200) {
          uni.showToast({
            title: this.isReset ? '密码重置成功' : '密码设置成功',
            icon: 'success'
          })

          // 更新本地用户信息，标记已设置密码
          const userInfo = uni.getStorageSync('userInfo')
          if (userInfo) {
            userInfo.hasPassword = true
            uni.setStorageSync('userInfo', userInfo)
          }

          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(res?.message || (this.isReset ? '重置失败' : '设置失败'))
        }
        
      } catch (error) {
        console.error('设置密码失败:', error)
        uni.showToast({
          title: error.message || (this.isReset ? '重置失败，请重试' : '设置失败，请重试'),
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
        this.isSubmitting = false
      }
    }
  },
  
  // 组件销毁时清除定时器
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style>
.sms-password-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 0 30rpx;
}

.page-header {
  padding: 60rpx 0 40rpx;
  text-align: center;
}

.header-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.header-subtitle {
  font-size: 28rpx;
  color: #666;
}

.form-item {
  background-color: #fff;
  margin-bottom: 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.phone-display {
  font-size: 28rpx;
  color: #4080FF;
  font-weight: 500;
}

.code-wrapper {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1px solid #eee;
  border-radius: 40rpx;
  font-size: 28rpx;
  background-color: #f8f8f8;
}

.code-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #4080FF;
  color: #fff;
  font-size: 24rpx;
  border-radius: 40rpx;
  text-align: center;
}

.code-btn:disabled {
  background-color: #ccc;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.form-input {
  flex: 1;
  height: 80rpx;
  padding: 0 80rpx 0 20rpx;
  border: 1px solid #eee;
  border-radius: 40rpx;
  font-size: 28rpx;
  background-color: #f8f8f8;
}

.password-toggle {
  position: absolute;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.toggle-icon {
  font-size: 32rpx;
}

.password-tips {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 20rpx;
  margin-bottom: 40rpx;
}

.tips-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 20rpx;
}

.tips-item {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
  transition: color 0.3s;
}

.tips-item.valid {
  color: #4080FF;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #4080FF;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
}

.submit-btn:disabled {
  background-color: #ccc;
}
</style>
